package com.demo.gateway.redis;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import cn.hutool.core.date.DateUtil;
import lombok.Getter;


@Component
public class RedisClient {
	
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    public void set(String key, String value, long timeOut, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeOut, timeUnit);
    }
    
    /**
     * 存储的key失效时间为当天23点59分59秒
     * @param key
     * @param value
     * @param date
     */
    public void set(String key, String value, Date date) {
    	String sfm = " 23:59:59";
    	String dqrq = DateUtil.today();
    	String sedsj = dqrq + sfm;
    	long sedmill = DateUtil.parseDateTime(sedsj).getTime();
    	long timeOut = sedmill - date.getTime();
        redisTemplate.opsForValue().set(key, value, timeOut, TimeUnit.MILLISECONDS);
    }

    public String getString(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public double getDouble(String key) {
        String value = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(value)) {
            return Double.valueOf(value);
        }
        return 0.0;
    }

    public int getInteger(String key) {
        String value = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(value)) {
            return Integer.valueOf(value);
        }
        return 0;
    }

    public boolean isExist(String key) {
        return redisTemplate.hasKey(key);
    }

    public void delete(String key) {
        if (redisTemplate.hasKey(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 存储从value开始递增
     * @param key
     */
    public void incr(String key) {
        redisTemplate.boundValueOps(key).increment(1);
    }
    
    
    /**
     * 获取key的剩余时间
     * @param key
     */
    public long getExpire(String key) {
        return redisTemplate.boundValueOps(key).getExpire();
    }
    
    public Long getExpire(String key, TimeUnit timeUnit) {
        return redisTemplate.getExpire(key, timeUnit);
    }
    



}
